<template>
  <div class="order-list-container">
    <HomeNav />
    
    <!-- 订单列表区域 -->
    <div class="order-content">
      <!-- 标题栏 -->
      <div class="page-header">
        <h2>我的秒杀订单</h2>
        <el-tabs v-model="activeTab" @tab-click="handleTabChange">
          <el-tab-pane v-for="tab in tabList" :key="tab.name" :label="tab.label" :name="tab.name" />
        </el-tabs>
      </div>

      <!-- 订单列表 -->
      <div class="order-list" v-loading="loading">
        <div v-if="orderList.length > 0">
          <div class="order-item" v-for="order in orderList" :key="order.id">
            <div class="order-header">
              <span class="order-time">下单时间：{{ order.createTime }}</span>
              <span class="order-no">订单号：{{ order.orderNo }}</span>
              <span class="order-status" :class="order.status">{{ getStatusText(order.status) }}</span>
            </div>
            <div class="order-body" @click="handleOrderClick(order)">
              <img :src="order.productImage" :alt="order.productName" class="product-image">
              <div class="product-info">
                <h3 class="product-name">{{ order.productName }}</h3>
                <p class="product-brief">{{ order.productBrief }}</p>
                <div class="product-price">
                  <span class="price">￥{{ order.price }}</span>
                  <span class="count">x{{ order.count }}</span>
                </div>
              </div>
              <div class="order-action">
                <span class="total-amount">实付款：<em>￥{{ order.totalAmount }}</em></span>
                <div class="action-buttons">
                  <el-button 
                    v-if="order.status === 'unpaid'" 
                    type="danger" 
                    @click.stop="handlePay(order)"
                  >
                    立即付款
                  </el-button>
                  <el-button 
                    v-if="order.status === 'unpaid'" 
                    @click.stop="handleCancel(order)"
                  >
                    取消订单
                  </el-button>
                  <el-button 
                    v-if="order.status === 'completed'" 
                    type="primary" 
                    @click.stop="handleReview(order)"
                  >
                    评价
                  </el-button>
                  <el-button 
                    v-if="['completed', 'cancelled'].includes(order.status)" 
                    @click.stop="handleDelete(order)"
                  >
                    删除订单
                  </el-button>
                </div>
              </div>
            </div>
          </div>
        </div>
        <el-empty v-else description="暂无相关订单" />
      </div>

      <!-- 分页器 -->
      <div class="pagination" v-if="total > 0">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <HomeFooter />
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import HomeNav from '@/components/layout/HomeNav.vue'
import HomeFooter from '@/components/layout/HomeFooter.vue'

const router = useRouter()
const loading = ref(false)
const activeTab = ref('all')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 标签页配置
const tabList = [
  { label: '全部订单', name: 'all' },
  { label: '待付款', name: 'unpaid' },
  { label: '待发货', name: 'unshipped' },
  { label: '待收货', name: 'unreceived' },
  { label: '已完成', name: 'completed' }
]

// 模拟订单数据
const orderList = ref([
  {
    id: 1,
    orderNo: 'MS202306150001',
    createTime: '2023-06-15 10:00:00',
    status: 'unpaid',
    productName: '康佳(KONKA)580升 对开门冰箱',
    productImage: require('@/assets/imgs/goods/goods01.png'),
    productBrief: '高效节能，智能温控',
    price: 1899,
    count: 1,
    totalAmount: 1899
  },
  {
    id: 2,
    orderNo: 'MS202306150002',
    createTime: '2023-06-15 09:30:00',
    status: 'completed',
    productName: '小米(MI)Redmi K60 5G手机',
    productImage: require('@/assets/imgs/goods/goods02.jpg.avif'),
    productBrief: '骁龙8+旗舰处理器',
    price: 1999,
    count: 1,
    totalAmount: 1999
  }
])

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    unpaid: '待付款',
    unshipped: '待发货',
    unreceived: '待收货',
    completed: '已完成',
    cancelled: '已取消'
  }
  return statusMap[status] || status
}

// 处理订单点击
const handleOrderClick = (order) => {
  router.push(`/seckill/order/detail/${order.id}`)
}

// 处理支付
const handlePay = (order) => {
  router.push(`/seckill/order/pay?orderNo=${order.orderNo}`)
}

// 处理取消订单
const handleCancel = async (order) => {
  try {
    await ElMessageBox.confirm('确定要取消该订单吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    // TODO: 调用取消订单接口
    ElMessage.success('订单已取消')
    order.status = 'cancelled'
  } catch (error) {
    console.log('取消操作')
  }
}

// 处理删除订单
const handleDelete = async (order) => {
  try {
    await ElMessageBox.confirm('确定要删除该订单吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    // TODO: 调用删除订单接口
    const index = orderList.value.findIndex(item => item.id === order.id)
    if (index > -1) {
      orderList.value.splice(index, 1)
    }
    ElMessage.success('订单已删除')
  } catch (error) {
    console.log('取消删除')
  }
}

// 处理评价
const handleReview = (order) => {
  router.push(`/order/review/${order.id}`)
}

// 处理标签页切换
const handleTabChange = (tab) => {
  // TODO: 根据标签页筛选订单
  console.log('切换到:', tab.props.name)
}

// 处理分页
const handleSizeChange = (val) => {
  pageSize.value = val
  loadOrders()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  loadOrders()
}

// 加载订单数据
const loadOrders = async () => {
  loading.value = true
  try {
    // TODO: 调用获取订单列表接口
    // 模拟加载延迟
    await new Promise(resolve => setTimeout(resolve, 500))
    total.value = orderList.value.length
  } catch (error) {
    ElMessage.error('加载订单失败')
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  loadOrders()
})
</script>

<style lang="scss" scoped>
.order-list-container {
  min-height: 100vh;
  background-color: #f5f5f5;

  .order-content {
    max-width: 1200px;
    margin: 20px auto;
    padding: 0 20px;

    .page-header {
      background: #fff;
      padding: 20px;
      border-radius: 8px;
      margin-bottom: 20px;

      h2 {
        margin: 0 0 20px;
        font-size: 24px;
        color: #333;
      }
    }

    .order-list {
      .order-item {
        background: #fff;
        border-radius: 8px;
        margin-bottom: 20px;
        overflow: hidden;

        .order-header {
          padding: 15px 20px;
          background: #f8f8f8;
          display: flex;
          align-items: center;
          
          .order-time {
            color: #666;
            margin-right: 30px;
          }

          .order-no {
            color: #666;
            flex: 1;
          }

          .order-status {
            font-weight: bold;

            &.unpaid { color: #ff4d4f; }
            &.unshipped { color: #faad14; }
            &.unreceived { color: #1890ff; }
            &.completed { color: #52c41a; }
            &.cancelled { color: #999; }
          }
        }

        .order-body {
          padding: 20px;
          display: flex;
          align-items: center;
          gap: 20px;
          cursor: pointer;
          transition: all 0.3s;

          &:hover {
            background: #fafafa;
          }

          .product-image {
            width: 100px;
            height: 100px;
            object-fit: cover;
            border-radius: 4px;
          }

          .product-info {
            flex: 1;

            .product-name {
              margin: 0 0 10px;
              font-size: 16px;
              color: #333;
            }

            .product-brief {
              color: #666;
              margin-bottom: 10px;
              font-size: 14px;
            }

            .product-price {
              color: #999;
              font-size: 14px;

              .price {
                color: #ff4d4f;
                font-weight: bold;
                margin-right: 10px;
              }
            }
          }

          .order-action {
            text-align: right;
            min-width: 200px;

            .total-amount {
              display: block;
              margin-bottom: 15px;
              color: #666;
              font-size: 14px;

              em {
                font-style: normal;
                color: #ff4d4f;
                font-size: 20px;
                font-weight: bold;
              }
            }

            .action-buttons {
              display: flex;
              flex-direction: column;
              gap: 10px;
              align-items: flex-end;
            }
          }
        }
      }
    }

    .pagination {
      text-align: right;
      margin-top: 20px;
      padding: 20px;
      background: #fff;
      border-radius: 8px;
    }
  }
}
</style>
